package org.i1510.common.utils.web;

import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.ser.StdSerializerProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.i1510.common.utils.web.NullSerializer;
public class ResultMapper {
	
	private static Logger logger =LoggerFactory.getLogger(ResultMapper.class);
	
	private HashMap<String , Object> map;
	private ObjectMapper mapper;
	/**
	 * 是否通过 resultCode = 0 未通过 resultCode = 1 通过
	 */
	private Boolean isPass;
	
	/**
	*@Author Rambo
	*@Desc：否通过 resultCode = 0 未通过 resultCode = 1 通过
	*@return TODO
	*@Version  ResultMapper.java,v 1.1 2013-12-26 下午2:04:52 
	*/
	public Boolean getIsPass() {
		return isPass;
	}

	public void setIsPass(Boolean isPass) {
		this.isPass = isPass;
	}

	public ResultMapper(String resultCode , String resultMsg) {
		map = new HashMap<String , Object>();
		map.put("code", resultCode);
		map.put("result", resultMsg);
		if(null != resultCode && resultCode.equalsIgnoreCase("0")){
			isPass = false;
		}else{
			isPass = true;
		}
	}
	
	public static ResultMapper generateFailure() {
		return new ResultMapper("0" , "failure");
	}
	
	public static ResultMapper generateFailure(String resultMsg) {
		return new ResultMapper("0" , resultMsg);
	}
	
	public static ResultMapper generateSuccess() {
		return new ResultMapper("1" , "success");
	}
	
	public static ResultMapper generateSuccess(String resultMsg) {
		return new ResultMapper("1" ,resultMsg);
	}
	
	public void toJson(Writer writer) {
		try {
			StdSerializerProvider sp = new StdSerializerProvider();
			sp.setNullValueSerializer(new NullSerializer());
			mapper = new ObjectMapper();
			mapper.setSerializerProvider(sp);
			mapper.writeValue(writer, map);
		} catch (IOException e) {
			logger.warn("write to json string error:" + map, e);
		}
	}
	
	public String toJson() {
		try {
			StdSerializerProvider sp = new StdSerializerProvider();
			sp.setNullValueSerializer(new NullSerializer());
			mapper = new ObjectMapper();
			mapper.setSerializerProvider(sp);
			mapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
			return mapper.writeValueAsString(map);
		} catch (IOException e) {
			logger.warn("write to json string error:" + map, e);
			return null;
		}
	}
	
	public void appendResult(String name , Object object) {
		if(null == object){
			map.put(name, "");
		}else{
			map.put(name, object);
		}
		
	}
	
	
	public HashMap<String, Object> getMap() {
		return map;
	}

	public void appendResult(String name , Object[] array) {
		map.put(name, ArrayUtils.toMap(array));
	}
	
	
	@Override
	public String toString() {
		return ToStringBuilder.reflectionToString(this);
	}
}
